<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="500px">
        <el-form :model="dialogForm" size="small" :rules="rules" ref="dialogFormRef">
            <el-form-item prop="symbolName" label="符号名称">
                <el-input v-model="dialogForm.symbolName" :disabled="type === 'view'" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="symbolCode" label="符号编码">
                <el-input v-model="dialogForm.symbolCode" :disabled="type === 'view'" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="symbolType" label="符号类型">
                <el-select v-model="dialogForm.symbolType" :disabled="type === 'view'" style="width:100%">
                    <el-option v-for="(item,index) in symbolTypeList" :key="'symbolType'+index" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="symbolKey" label="符号" v-if="dialogForm.symbolType === 'TEXT'">
                <el-input v-model="dialogForm.symbolKey" :disabled="type === 'view'" type="textarea"
                    placeholder="请输入" />
            </el-form-item>

            <el-form-item prop="symbolKey" label="符号"
                v-if="dialogForm.symbolType === 'IMAGE' || dialogForm.symbolType === 'FORMULA_DATA'">
                <img v-if="imgUrl" :src="imgUrl" :key="uploadImage" />
                <el-button @click="open('symbol')">打开符号编辑器</el-button>
            </el-form-item>
            <el-form-item prop="symbolValue" label="符号右值">
                <el-input v-model="dialogForm.symbolValue" :disabled="type === 'view'" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="symbolDescribeType" label="符号单位类型">
                <el-select v-model="dialogForm.symbolDescribeType" :disabled="type === 'view'" style="width:100%">
                    <el-option v-for="(item,index) in symbolTypeList" :key="'symbolDescribeType'+index"
                        :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="symbolDescribe" label="符号单位" v-if="dialogForm.symbolDescribeType === 'TEXT'">
                <el-input v-model="dialogForm.symbolDescribe" :disabled="type === 'view'" type="textarea"
                    :autosize="{minRows:2}" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="symbolDescribe" label="符号单位"
                v-if="dialogForm.symbolDescribeType === 'IMAGE' || dialogForm.symbolDescribeType === 'FORMULA_DATA'">
                <img v-if="desimgUrl" :src="desimgUrl" :key="uploadDesImage" />
                <el-button @click="open('des')">打开符号编辑器</el-button>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="handleSure" v-if="type !== 'view'">确 定</el-button>
        </span>
        <el-dialog :visible.sync="formulaVisible" :modal="false">
            <iframe v-show="formulaVisible" id="myiframe" :src="baseURL"
                style="border: none; width: 850px; height: 500px;" ref="formulaRef"></iframe>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleFormulaClose">取 消</el-button>
                <el-button :disabled="uploadSubmit" type="primary" @click="handleFormulaSure">确 定</el-button>
            </span>
        </el-dialog>
    </el-dialog>
</template>

<script>
    import { getToken } from "@/utils/auth";
    import { addAlgorithmSymbol, editAlgorithmSymbol } from '@/api/symbol.js'
    import { uploadFile } from '@/api'
    export default {
        props: {
            type: {
                type: String,
                default: 'add'
            },
            datas: {
                type: Object,
                default: () => ({})
            },
        },
        data() {
            return {
                formulaVisible: false,
                title: '',
                dialogVisible: true,
                dialogForm: {
                    id: undefined,
                    symbolName: '',
                    symbolCode: '',
                    symbolType: '',
                    symbolKey: '',
                    symbolValue: '',
                    symbolDescribe: '',
                    symbolDescribeType: ''
                },
                imgUploadUrl: process.env.VUE_APP_BASE_API + "/editor/file/upload", // 上传的图片服务器地址
                // imgUploadUrl:  'http://10.11.54.239/prod-api' + "/editor/file/upload", // 上传的图片服务器地址
                headers: {
                    Authorization: "Bearer " + getToken()
                },
                imageUrl: '',
                rules: {
                    symbolCode: [{ required: true, message: '符号编码不能为空', trigger: 'blur' }],
                    symbolKey: [{ required: true, message: '符号不能为空', trigger: 'blur' }],
                    symbolType: [{ required: true, message: '符号类型不能为空', trigger: 'change' }],
                    symbolName: [{ required: true, message: '符号名称不能为空', trigger: 'blur' }]
                },
                symbolTypeList: [
                    {
                        label: '图片符号',
                        value: 'IMAGE'
                    },
                    {
                        label: '图片+LATEX符号',
                        value: 'FORMULA_DATA'
                    },
                    {
                        label: '纯文本',
                        value: 'TEXT'
                    }
                ],
                desImageUrl: '',
                baseURL: "",
                formulaImage: null,
                uploadImage: null,
                uploadDesImage: null,
                imgUrl: null,
                desimgUrl: null,
                uploadSubmit: false,
                receivedIds: new Set(),
                sendHttp: false,
                eventData: null
            }
        },
        mounted() {
            this.initData();
            const that = this;
            window.removeEventListener('message', function (event) {
                that.handleMessage(event.data)
            });
            window.addEventListener('message', function (event) {
                that.handleMessage(event.data)
            });
        },
        methods: {
            getImgSrc(ossId) {
                return window.location.origin + '/prod-api/editor/file/download/' + ossId
                // return 'http://10.11.54.239/prod-api/editor/file/download/' +ossId
            },
            async handleMessage(event) {
                if (event.cmd === 'formulaInsertContent' && event.mceAction == "execCommand" && !this.sendHttp) {
                    const { data, latex } = event.value;
                    this.formulaImage = data.img
                    this.formulaVisible = false;
                    this.eventData = event.value
                }
            },
            handleFormulaClose() {
                this.formulaVisible = false;
            },
            handleFormulaSure() {
                const iframe = this.$refs.formulaRef
                iframe?.contentWindow.postMessage('save', '*')
                this.uploadSubmit = true;
            },
            base64ToImage(base64, fileName, type) {
                const byteCharecters = atob(base64.split(',')[1]);
                const byteNumbers = new Array(byteCharecters.length);
                for (let i = 0; i < byteCharecters.length; i++) {
                    byteNumbers[i] = byteCharecters.charCodeAt(i);
                }
                const byteArray = new Uint8Array(byteNumbers);
                const blob = new Blob([byteArray], { type: type });
                const file = new File([blob], fileName, { type: type });
                return file;
            },
            open(type) {
                this.editType = type;
                this.formulaVisible = true;
                // const iframe = this.$refs.formulaRef;
                this.baseURL = window.location.origin + '/tinymce/plugins/kityformula/index.html'
                // iframe.contentWindow.postMessage('save_variable_formula', '*')
            },
            initData() {
                if (this.datas.id) {
                    this.dialogForm = {
                        id: this.datas.id,
                        symbolName: this.datas.symbolName,
                        symbolCode: this.datas.symbolCode,
                        symbolType: this.datas.symbolType,
                        symbolKey: this.datas.symbolKey,
                        symbolValue: this.datas.symbolValue,
                        symbolDescribe: this.datas.symbolDescribe,
                        symbolDescribeType: this.datas.symbolDescribeType
                    }
                } else {
                    this.dialogForm = {
                        id: undefined,
                        symbolName: '',
                        symbolCode: '',
                        symbolType: '',
                        symbolKey: '',
                        symbolValue: '',
                        symbolDescribe: '',
                        symbolDescribeType: ''
                    }
                }
                if (this.dialogForm.symbolType === 'IMAGE') {
                    this.imgUrl = window.location.origin + '/prod-api/editor/file/download/' + this.dialogForm.symbolKey
                }
                if (this.dialogForm.symbolType === 'FORMULA_DATA') {
                    const obj = JSON.parse(this.dialogForm.symbolKey);
                    this.imgUrl = obj?.url;
                }
                if (this.dialogForm.symbolDescribeType === 'IMAGE') {
                    this.desimgUrl = window.location.origin + '/prod-api/editor/file/download/' + this.dialogForm.symbolDescribe
                }
                if (this.dialogForm.symbolDescribeType === 'FORMULA_DATA') {
                    const obj = JSON.parse(this.dialogForm.symbolDescribe);
                    this.desimgUrl = obj?.url;
                }

            },
            handleClose() {
                this.$emit('on-close');
            },
            handleSymbolSuccess(res, file) {
                this.dialogForm.symbolKey = res.data
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            handleSuccess(res, file) {
                this.dialogForm.symbolDescribe = res.data
                this.desImageUrl = URL.createObjectURL(file.raw);
            },
            beforeSymbolUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt5M = file.size / 1024 / 1024 < 5;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt5M) {
                    this.$message.error('上传头像图片大小不能超过 5MB!');
                }
                return isJPG && isLt5M;
            },
            async handleSure() {
                const file = this.base64ToImage(this.formulaImage, "符号单位", 'image/jpeg');
                const formData = new FormData();
                formData.append("file", file);
                this.sendHttp = true;

                await uploadFile(formData).then(res => {
                    console.log("上传文件")
                    console.log(res);
                    const { data, latex } = this.eventData;
                    if (this.editType == 'des') {
                        this.uploadDesImage = res?.data;
                        this.desimgUrl = this.getImgSrc(this.uploadDesImage)
                        this.dialogForm.symbolDescribe = res.data
                        if (this.dialogForm.symbolDescribeType == 'FORMULA_DATA') {
                            this.dialogForm.symbolDescribe = JSON.stringify({ latex: latex, url: this.desimgUrl })
                        }
                    } else {
                        this.uploadImage = res?.data;
                        this.formulaVisible = false;
                        this.imgUrl = this.getImgSrc(this.uploadImage)
                        this.dialogForm.symbolKey = res.data
                        if (this.dialogForm.symbolType == 'FORMULA_DATA') {
                            this.dialogForm.symbolKey = JSON.stringify({ latex: latex, url: this.imgUrl })
                        }
                    }
                    this.uploadSubmit = false;
                    this.receivedIds = new Set();
                    this.sendHttp = false;
                })

                this.$refs.dialogFormRef.validate((valid) => {
                    if (valid) {
                        if (this.type === 'edit') {
                            editAlgorithmSymbol(this.dialogForm).then(res => {
                                this.$message.success('编辑成功！')
                                this.$emit('on-sure')
                                this.handleClose()
                            })
                        } else {
                            addAlgorithmSymbol(this.dialogForm).then(res => {
                                this.$message.success('新增成功！')
                                this.$emit('on-sure')
                                this.handleClose()
                            })
                        }
                    } else {
                        this.$message.error('请填写必填信息！')
                        return false;
                    }
                });
            }
        },
        beforeDestroy() {
            const iframeDom = document.getElementById("myiframe");
            if (iframeDom && iframeDom.parentNode) {
                iframeDom.src = "about:blank";
                iframeDom.parentNode.removeChild(iframeDom);
            }
        }
    }
</script>

<style scope>
    .symbol-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .symbol-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .symbol-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }

    .symbol {
        width: 50px;
        height: 50px;
        display: block;
    }
</style>